<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a lay-href="">主页</a>
    <a><cite>码商订单列表</cite></a>
  </div>
</div>
<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-tab layui-tab-brief">
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div class="layui-row">
            <div class="layui-form">
              <div class="layui-form-item">
                <div class="layui-input-inline">
                  <input type="text" name="startTime" id="startTime" autocomplete="off" placeholder="开始时间" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="endTime" id="endTime" autocomplete="off" placeholder="结束时间" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="codeName" id="codeName" placeholder="二维码标识" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="orderNo" id="orderNo" placeholder="订单号" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="mchOrderNo" id="mchOrderNo" placeholder="商户订单号" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <input type="text" name="clientIp" id="clientIp" placeholder="客户IP" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <select name="codeBusId" id="codeBusId" lay-filter="codeBusId" lay-search="">
                    <option value="">选择所属码商</option>
                  </select>
                </div>
                <div class="layui-input-inline">
                  <select name="mchId" id="mchId" lay-filter="mchId" lay-search="">
                    <option value="">选择所属商户</option>
                  </select>
                </div>
                <div class="layui-input-inline">
                  <select name="status" id="status" lay-search="">
                    <option value="">订单状态</option>
                    <option value="3">业务完成</option>
                    <option value="2">支付成功</option>
                    <option value="1">支付中</option>
                    <option value="0">订单生成</option>
                    <option value="-1">支付失败</option>
                    <option value="-2">订单过期</option>
                  </select>
                </div>
                <div class="layui-input-inline">
                  <button id="search" class="layui-btn" data-type="reload">搜索</button>
                </div>
                <div class="layui-input-inline">
                  <input type="checkbox" name="close" lay-filter="refreshSwitch" layui-tip="" lay-skin="switch" lay-text="自动刷新开|自动刷新关">
                </div>
<!--                <div class="layui-input-inline">-->
<!--                  <select name="interest" id="refreshTime" lay-filter="refreshTime">-->
<!--                    <option value="1">30秒</option>-->
<!--                    <option value="2">一分钟</option>-->
<!--                    <option value="120">两分钟</option>-->
<!--                    <option value="180">三分钟</option>-->
<!--                    <option value="240">四分钟</option>-->
<!--                    <option value="300">五分钟</option>-->
<!--                  </select>-->
<!--                </div>-->
              </div>
              <div class="layui-form-item" style="margin-top: 5px;">
                <blockquote class="layui-elem-quote" id="amountTip">
                  提交订单数:<sapn id="allTotalCount" style="color: dodgerblue; margin-right: 10px;"></sapn>
                  订单总金额:<span id="allTotalAmount" style="color: blueviolet; margin-right: 10px;"></span>
                  已付订单数:<span id="successTotalCount" style="color: blue; margin-right: 10px;"></span>
                  已付总金额:<span id="successTotalAmount" style="color: blue; margin-right: 10px;"></span>
                  码商总收入:<span id="totalProfit" style="color: darkgreen; margin-right: 10px;"></span>
                  码商收入:<span id="totalCodeBusProfit" style="color: green; margin-right: 10px;"></span>
                  代理收入:<span id="totalAgentProfit" style="color: green; margin-right: 10px;"></span>
                  会员收入:<span id="totalUserProfit" style="color: green; margin-right: 10px;"></span>
                  未付订单数:<span id="failTotalCount" style="color: red; margin-right: 10px;"></span>
                  未付总金额:<span id="failTotalAmount" style="color: orangered; margin-right: 10px;"></span>
                  成功率:<span id="sucRate" style="color: green; margin-right: 10px;"></span>
                </blockquote>
              </div>
            </div>
          </div>
          <table id="Code_Order_dataAll" lay-filter="Code_Order_dataAll"></table>
        </div>
      </div>
    </div>
  </div>
</div>
<style>
  .imgDiv {
    width: 500px;
    height: 500px;
    vertical-align: middle;
    display: table-cell;
    text-align: center;
  }
</style>
<script type="text/html" id="operateBar">
<!--  {{#  if(d.status == 0 || d.status == 1){ }} -->
<!--  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="confirm">确认</a>-->
<!--  {{#  } }}-->
<a class="layui-btn layui-btn-xs layui-btn-primary" title="点击查看二维码" lay-event="viewQr"><i class="layui-icon">&#xe64a;</i></a>
<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">详情</a>
{{#  if(d.status != 2 && d.status != 3){ }}
<a class="layui-btn layui-btn-xs layui-btn-danger" title="修改实收金额" lay-event="updateAmount"><i class="layui-icon">&#xe642;</i></a>
{{#  } }}
</script>
<script>
layui.use(['admin', 'table', 'util', 'laydate'], function(){
  var $ = layui.$
  ,admin = layui.admin
  ,table = layui.table
  ,element = layui.element
  ,laydate = layui.laydate
  ,form = layui.form;

  element.render('breadcrumb', 'breadcrumb');

  $.setCountResult = function(startTime, endTime, mchId, codeBusId, codeName, orderNo, mchOrderNo, status, clientIp) {
    admin.req({
      type: 'get',
      url: layui.setter.baseUrl + '/code/order/count',
      data: {
        mchId: mchId,
        codeBusId: codeBusId,
        codeName: codeName,
        orderNo: orderNo,
        mchOrderNo: mchOrderNo,
        status : status,
        clientIp : clientIp,
        startTime : startTime,
        endTime : endTime
      },
      error: function(err){
        layer.alert(JSON.stringify(err.field), {
          title: '错误提示'
        })
      },
      success: function(res){
        if(res.code == 0){
          $('#allTotalCount').html(res.data.allTotalCount);
          $('#allTotalAmount').html("￥" + res.data.allTotalAmount);
          $('#successTotalCount').html(res.data.successTotalCount);
          $('#successTotalAmount').html("￥" + res.data.successTotalAmount);
          $('#totalProfit').html("￥" + res.data.totalProfit);
          $('#totalCodeBusProfit').html("￥" + res.data.totalCodeBusProfit);
          $('#totalAgentProfit').html("￥" + res.data.totalAgentProfit);
          $('#totalUserProfit').html("￥" + res.data.totalUserProfit);
          $('#failTotalCount').html(res.data.failTotalCount);
          $('#failTotalAmount').html("￥" + res.data.failTotalAmount);
          $('#sucRate').html((res.data.successTotalCount/res.data.allTotalCount * 100).toFixed(2) + "%");
        }
      }
    });
  };

  var tplStatus = function (d) {
    if(d.status == 0) {
      return "<span style='color: yellowgreen'>订单生成</span>";
    }else if(d.status == 1) {
      return "<span style='color: orangered'>支付中</span>";
    }else if(d.status == 2) {
      return "<span style='color: blueviolet'>支付成功</span>";
    }else if(d.status == 3) {
      return "<span style='color: blue'>处理完成</span>";
    }else if(d.status == -1) {
      return "<span style='color: darkred'>支付失败</span>";
    }else if(d.status == -2) {
      return "<span style='color: red'>订单过期</span>";
    }
  };

  var tplPhase = function (d) {
    if(d.operatePhase == 0) {
      return "生成订单";
    }else if(d.operatePhase == 1) {
      return "进入订单页";
    }else if(d.operatePhase == 2) {
      return "点击跳转";
    }else if(d.operatePhase == 3) {
      return "扫码";
    }else if(d.operatePhase == 4) {
      return "进入app";
    }else if(d.operatePhase == 5) {
      return "转账";
    }
  };

  var tplOS = function (d) {
    if (d.osType == 1) {
      return '<i class="layui-icon" style="color: silver">&#xe684;</i>';
    } else if (d.osType == 2) {
      return '<i class="layui-icon" style="color: green">&#xe680;</i>';
    } else {
      return '<i class="layui-icon">&#xe678;</i>';
    }
  };

  var tplConfirmTime = function (d) {
    if (d.confirmTime != null) {
      return layui.util.toDateString(d.confirmTime, "HH:mm:ss");
    } else {
      return "";
    }
  };

  admin.req({
    type: 'get',
    url: layui.setter.baseUrl + '/code/user/getUserByType?type=3',
    success: function (res) {
      if (res.code == 0) {
        var options;
        for (i in res.data) {
          var e = res.data[i];
          options += '<option value="' + e.id + '">' + e.realName + ' (' + e.username + ')</option>'
        }
        $("#codeBusId").append(options);
        form.render();
      }
    }
  });

  admin.req({
    type: 'get',
    url: layui.setter.baseUrl + '/mch_info/getAll',
    success: function (res) {
      if (res.code == 0) {
        var options;
        for (i in res.data) {
          var e = res.data[i];
          options += '<option value="' + e.mchId + '">' + e.name + ' (' + e.userName + ')</option>'
        }
        $("#mchId").append(options);
        form.render();
      }
    }
  });

  var dateTime = new Date();
  dateTime.setDate(dateTime.getDate()-1);
  dateTime = new Date(dateTime);
  var startTimeDefault = layui.util.toDateString(dateTime, "yyyy-MM-dd 00:00:00")
  $.setCountResult(startTimeDefault);
  //用户列表
  table.render({
    elem: '#Code_Order_dataAll'
    ,url: layui.setter.baseUrl + '/code/order/list' //用户列表接口
    ,where: {
        access_token: layui.data(layui.setter.tableName).access_token,
        startTime : startTimeDefault
    }
    ,id: 'tableReload'
    ,page: true
    ,cols: [[
      {field: 'codeBusId', title: '码商ID', width: 75}
      ,{field: 'username', title: '收款人'}
      ,{field: 'codeName', title: '二维码标识'}
      ,{field: 'productName', title: '产品名称'}
      ,{field: 'mchName', title: '商户名称'}
      ,{field: 'mchOrderNo', title: '商户订单号', width: 220}
      ,{field: 'orderNo', title: '订单号', width: 190}
      ,{field: 'amount', title: '金额', width: 90}
      // ,{field: 'userRate', title: '费率', templet: '<div>{{ ((d.userRate+d.codeBusRate+d.agentRate)*100).toFixed(2) }}%</div>'}
      ,{field: 'status', title: '状态', width: 90, templet: tplStatus}
      ,{field: 'operatePhase', title: '操作阶段', templet: tplPhase, width: 100}
      ,{field: 'clientIp', title: '客户IP', width: 140}
      ,{field: 'osType', title: '系统', templet: tplOS}
      ,{field: 'createTime', title: '订单时间', width: 130, templet: '<div>{{ layui.util.toDateString(d.createTime, "MM-dd HH:mm:ss") }}</div>'}
      ,{field: 'confirmTime', title: '确认时间', width: 90, templet: tplConfirmTime}
      ,{field: 'edit', title: '操作', width: 150, toolbar: '#operateBar' }
    ]]
    ,skin: 'line'
  });

  //监听工具条
  table.on('tool(Code_Order_dataAll)', function (obj) {
    var data = obj.data;
    if (obj.event === 'detail') {
      location.hash = "/code/order/detail/id=" + data.id;
    } else if (obj.event === 'viewQr') {
      var codeUrl = "";
      admin.req({
        type: 'get',
        url: layui.setter.baseUrl + '/code/qr/view',
        data: {
          id: data.codeId,
        },
        success: function (res) {
          if (res.code == 0) {
            codeUrl = res.data;
            layer.open({
              type: 1,
              title: '查看二维码',
              area: ['500px', '550px'],
              shadeClose: true,
              content: '<div class="imgDiv"><img style="width:80%;height:80%;" src="' + codeUrl + '"></div>'
            });
          }
        }
      });
    } else if (obj.event === 'updateAmount') {
      layer.open({
        type: 1,
        title: '修改实收金额',
        area: ['400px', '500px'],
        shadeClose: true,
        btn: ['确认修改', '取消'],
        content: `
            <div class="layui-tab-content">
              <div class="layui-form-item">
                <label class="layui-form-label">码商用户</label>
                <div class="layui-input-inline">
                  <input type="text" class="layui-input" disabled="disabled" value="`+data.username+`">
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label">收款人</label>
                <div class="layui-input-inline">
                  <input type="text" class="layui-input" disabled="disabled" value="`+data.codeName+`">
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label">订单号</label>
                <div class="layui-input-inline">
                  <input type="text" class="layui-input" disabled="disabled" value="`+data.orderNo+`">
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label">商户订单号</label>
                <div class="layui-input-inline">
                  <input type="text" class="layui-input" disabled="disabled" value="`+data.mchOrderNo+`" style="width: 200px">
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label">订单金额</label>
                <div class="layui-input-inline">
                  <input type="text" class="layui-input" disabled="disabled" value="`+data.amount+`">
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label"><span style="color: red;">* </span>到账金额</label>
                <div class="layui-input-inline">
                  <input type="text" id="newAmount" class="layui-input" placeholder="请输入实际到账金额" autocomplete="off">
                </div>
              </div>
              <div class="layui-form-item">
                <label class="layui-form-label"><span style="color: red;">* </span>超级密码</label>
                <div class="layui-input-inline">
                  <input type="password" id="password" class="layui-input" placeholder="请输入超级密码" autocomplete="off">
                </div>
              </div>
            </div>
            `
        ,yes: function(index, layero){
          var newAmount = $("#newAmount").val();
          var password = $("#password").val();
          if(!newAmount){
            layer.msg("请输入实际到账金额");
            return false;
          }
          if(!password){
            layer.msg("请输入超级密码");
            return false;
          }
          admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/code/order/updateAmount',
            data: {
              id: data.id,
              newAmount: newAmount,
              password: password,
            },
            success: function (res) {
              layer.close(index);
              if (res.code == 0) {
                layer.msg('修改到账金额成功', {
                  icon: 1
                });
                table.reload("tableReload");
              } else {
                layer.msg(res.msg);
                return false;
              }
            }
          });
        }
        ,btn2: function(index, layero){
          //按钮【按钮一】的回调
        }
      });
    } else if (obj.event === 'confirm') {
      layer.confirm('确认收款:' + data.amount + '元?,一但确认不可追回!!!', function (index) {
        admin.req({
          type: 'get',
          url: layui.setter.baseUrl + '/code/order/confirm',
          data: {
            id: data.id,
          },
          success: function (res) {
            layer.close(index);
            if (res.code == 0) {
              layer.msg('确认成功', {
                icon: 1
              });
              table.reload("tableReload");
            } else {
              layer.msg(res.msg);
            }
          }
        });
      });
    }
  });

  //监听指定开关
  form.on('switch(refreshSwitch)', function (data) {
    if (this.checked) {
      autoRefresh();
      layer.msg('自动刷新已开启,每间隔30秒刷新一次列表数据');
    } else {
      clearInterval(window.refreshInterval);
      layer.msg('自动刷新已停止');
    }
  });

  clearInterval(window.refreshInterval);
  window.refreshInterval = null;
  // 自动刷新逻辑
  var autoRefresh = function () {
    var refreshTime = 30;
    window.refreshInterval = setInterval(function () {
      if(layui.router().href == "/code/order/list") {
        $("#search").click();
      }
    }, refreshTime * 1000);
  };

  // 搜索
  var $ = layui.$, active = {
    reload: function(){
      var mchId = $('#mchId').val();
      var codeBusId = $('#codeBusId').val();
      var codeName = $('#codeName').val();
      var orderNo = $('#orderNo').val();
      var mchOrderNo = $('#mchOrderNo').val();
      var status = $('#status').val();
      var clientIp = $('#clientIp').val();
      var startTime = $('#startTime').val();
      var endTime = $('#endTime').val();

      $.setCountResult(startTime, endTime, mchId, codeBusId, codeName, orderNo, mchOrderNo, status, clientIp);

      //执行重载
      table.reload('tableReload', {
        page: {
          curr: 1 //重新从第 1 页开始
        }
        ,where: {
          mchId: mchId,
          codeBusId: codeBusId,
          codeName: codeName,
          orderNo: orderNo,
          mchOrderNo: mchOrderNo,
          status : status,
          clientIp : clientIp,
          startTime : startTime,
          endTime : endTime
        }
      });
    }
  };
  $('#search').on('click', function() {
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
  });

  laydate.render({
    elem: '#startTime'
    ,type: 'datetime'
    ,value: startTimeDefault
    ,format: 'yyyy-MM-dd HH:mm:ss'
  });

  laydate.render({
    elem: '#endTime'
    ,type: 'datetime'
    // ,value: new Date(new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1)
    ,format: 'yyyy-MM-dd HH:mm:ss'
  });
  // 渲染表单
  form.render();
});
</script>